/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.parsing;

/**
 *
 * @author Clinton Begin
 */
public class GenericTokenParser {
  /**
   * 这里叫openToken，我更喜欢叫占位符前缀，如：${
   */
  private final String openToken;
  /**
   * closeToken ,即占位符后缀，如：},与openToken是一对
   */
  private final String closeToken;

  private final TokenHandler handler;

  public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
    this.openToken = openToken;
    this.closeToken = closeToken;
    this.handler = handler;
  }

  /**
   * 解析站位符的字符串，然后将字符串交给TokenHandler去处理，变为最终想要值
   * 例如：hello world ${language} 先解析出“language” ，然后交给TokenHandler(VariableTokenHandler)从变量获取对应值（假设是java）取代替站位符的内容。hello world java
   * @param text
   * @return
   */
  public String parse(String text) {
    if (text == null || text.isEmpty()) {
      return "";
    }
    // search open token
    //搜索openToken的位置
    int start = text.indexOf(openToken);
    //找不到说明，没有占位符，直接返回
    if (start == -1) {
      return text;
    }
    char[] src = text.toCharArray();
    int offset = 0; //起始查找的位置
    final StringBuilder builder = new StringBuilder();
    StringBuilder expression = null;  //用来存储匹配到占位符之间的key（openToken与closeToken之间的key，如：${driver}中的driver）
    while (start > -1) {
      //如果openToken前面一个是 \ 转义字符， 就忽略掉
      if (start > 0 && src[start - 1] == '\\') {
        // this open token is escaped. remove the backslash and continue.
        builder.append(src, offset, start - offset - 1).append(openToken);
        offset = start + openToken.length();
      } else {
        // found open token. let's search close token.
        //创建/重置expression
        if (expression == null) {
          expression = new StringBuilder();
        } else {
          //这里可以看到StringBuilder是怎么重用的
          expression.setLength(0);
        }
        // offset（起始位置） 到 openToken之间的内容，例如：java${varsion}，就是将java先添加到builder中
        builder.append(src, offset, start - offset);
        //在openToken的起始位置+openToken所占的字符长度，刚好就是key的起始位，重置offset
        offset = start + openToken.length();
        //在offset位置的基础上搜索closeToken
        int end = text.indexOf(closeToken, offset);
        while (end > -1) {
          //和上面一样处理转义字符
          if (end > offset && src[end - 1] == '\\') {
            // this close token is escaped. remove the backslash and continue.
            expression.append(src, offset, end - offset - 1).append(closeToken);
            offset = end + closeToken.length();
            end = text.indexOf(closeToken, offset);
          } else {
            //然后将openToken与closeToken之间的添加到expression中
            expression.append(src, offset, end - offset);
            break;
          }
        }
        if (end == -1) {
          // close token was not found.
          //如果没有找到，直接拼接
          builder.append(src, start, src.length - start);
          offset = src.length;
        } else {
          builder.append(handler.handleToken(expression.toString()));
          offset = end + closeToken.length();
        }
      }
      start = text.indexOf(openToken, offset);
    }
    if (offset < src.length) {
      builder.append(src, offset, src.length - offset);
    }
    return builder.toString();
  }
}
